package FileOperation;

import Book.*;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class loadBooks {
    public void fileLoad(List<Book> list) throws SQLException {
        // 1.建立数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java_mysql6?characterEncoding=utf8&&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("123456");

        // 2.建立连接
        Connection connection = dataSource.getConnection();
        // 3.创建sql语句
        String sql = "select * from bookshelf";
        // 4.解析sql语句并执行
        PreparedStatement statement = connection.prepareStatement(sql);
        ResultSet resultSet = statement.executeQuery();
        while (resultSet.next()) {
            String bookname = resultSet.getString(1);
            String author = resultSet.getString(2);
            double price = resultSet.getDouble(3);
            String type = resultSet.getString(4);
            boolean isBorrow = Boolean.parseBoolean(resultSet.getString(5));
            Book book = new Book(bookname, author, price, type, isBorrow);
            list.add(book);
        }
        resultSet.close();
        statement.close();
        connection.close();
    }
}
